package com.xf.common.core.page;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author FengYi
 * @Date 2020-06-15 15:55
 */
public class PageBuilder {


    public static <T> IPage<T> build(Map<String, Object> map) {
        long current = Long.valueOf(String.valueOf(map.get("current")));
        map.remove("current");
        long size = Long.valueOf(String.valueOf(map.get("size")));
        map.remove("size");
        String descs = String.valueOf(map.get("descs"));
        map.remove("descs");
        String ascs = String.valueOf(map.get("ascs"));
        map.remove("ascs");
        return build(current, size, ascs, descs);
    }

    public static <T> IPage<T> build(PageQuery pageQuery) {
        return build(pageQuery.getCurrent(), pageQuery.getSize(), pageQuery.getAscs(), pageQuery.getDescs());
    }

    public static <T> IPage<T> build(long current, long size){
        return build(current, size, null, null);
    }

    public static <T> IPage<T> build(long current, long size, String ascs, String descs){
        Page<T> page = new Page(current == 0 ? 1 : current, size == 0 ? 10 : size);
        List<OrderItem> orderItems = new ArrayList<>();
        if (!StringUtils.isEmpty(ascs)){
            orderItems.addAll(OrderItem.ascs(ascs.split(",")));
        }
        if (!StringUtils.isEmpty(descs)){
            orderItems.addAll(OrderItem.descs(descs.split(",")));
        }
        page.setOrders(orderItems);
        return page;
    }

}
